package sspatcher;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class Utilities {
    public static byte[] concatenateByteArrays(Collection<byte[]> arrays) {
        // 计算总长度
        int totalLength = 0;
        for (byte[] array : arrays) {
            totalLength += array.length;
        }

        // 创建新数组
        byte[] result = new byte[totalLength];

        // 复制到新数组
        int offset = 0;
        for (byte[] array : arrays) {
            System.arraycopy(array, 0, result, offset, array.length);
            offset += array.length;
        }

        return result;
    }

    /**
     * 计算消息的MD5值，返回小写
     * @param message
     * @return
     */
    public static String calcMD5LowerCast(byte[] message) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);  // should not happen
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : md5.digest(message)) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString().toLowerCase();
    }

    /**
     * 读取ini配置文件，得到映射。
     * @param file 配置文件，相对路径
     * @return
     * @throws IOException
     */
    public static Map<String, String> readIniFromFile(File file) throws IOException {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        Map<String, String> result = new HashMap<>();

        String line = br.readLine();
        while (null != line) {
            if (!line.trim().startsWith("#") && !line.trim().isEmpty()) { // 跳过行注释和空行
                int idx = line.indexOf('=');
                if (idx == -1) throw new IOException("Bad assignment at line:" + line);
                result.put(line.substring(0, idx).trim(), line.substring(idx + 1).trim());
            }
            line = br.readLine();
        }
        return result;
    }

    /**
     * 从文件读取列表，每行为一个元素。跳过注释
     * @param file 列表文件
     * @return
     * @throws IOException
     */
    public static List<String> readListFromFile(File file) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = br.readLine();
        List<String> result = new ArrayList<>();
        while (null != line) {
            if (!line.trim().startsWith("#")) { // 跳过行注释
                result.add(line);
            }
            line = br.readLine();
        }
        return result;
    }

    /**
     * 从带空格的十六进制字符串转换字节序列。
     * 为了兼容java7而未使用stream API
     * @param text 例："41 67 65 6E 74"
     * @return
     */
    public static byte[] getBytesFromSpacedHexText(String text) {
        String[] hexs = text.trim().split(" ");
        byte[] result = new byte[hexs.length];
        for (int i = 0; i < hexs.length; i++) {
            result[i] = (byte)Integer.parseInt(hexs[i], 16);
        }
        return result;
    }

    public static int parseIntAutoHex(String num) {
        if (num.startsWith("0x")) {
            return Integer.parseInt(num.substring(2), 16);
        }
        else {
            return Integer.parseInt(num);
        }
    }
}
